﻿using System;
using System.Text;
using Velocity4Net.Errors;
using Velocity4Net.Runtime.Parser;
using Velocity4Net.Util;

namespace Velocity4Net.Runtime.Directives
{

    /*
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     *
     *   http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing,
     * software distributed under the License is distributed on an
     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     * KIND, either express or implied.  See the License for the
     * specific language governing permissions and limitations
     * under the License.
     */






    /**
     *  Exception to indicate problem happened while constructing #macro()
     *
     *  For internal use in parser - not to be passed to app level
     *
     * @author <a href="mailto:geirm@apache.org">Geir Magnusson Jr.</a>
     * @author <a href="hps@intermeta.de">Henning P. Schmiedehausen</a>
     * @version $Id: MacroParseException.java 1780734 2017-01-28 19:21:08Z cbrisson $
     */
    public class MacroParseException
       :ParseException
       ,ExtendedParseException
{
    private readonly String templateName;

    /**
     * Version Id for serializable
     */
    private const long serialVersionUID = -4985224672336070689L;

    /**
     * @param msg
     * @param templateName
     * @param currentToken
     */
    public MacroParseException( String msg, String templateName, Token currentToken):base(msg + " at ")
    {
        this.currentToken = currentToken;
        this.templateName = templateName;
    }

    /**
     * returns the Template name where this exception occured.
     * @return The Template name where this exception occured.
     * @since 1.5
     */
    public String getTemplateName()
    {
        return templateName;
    }

    /**
     * returns the line number where this exception occured.
     * @return The line number where this exception occured.
     * @since 1.5
     */
    public int getLineNumber()
    {
        if ((currentToken != null) && (currentToken.next != null))
        {
            return currentToken.next.beginLine;
        }
        else if (currentToken != null)
        {
            return currentToken.beginLine;
        }
        else
        {
            return -1;
        }
    }

    /**
     * returns the column number where this exception occured.
     * @return The column number where this exception occured.
     * @since 1.5
     */
    public int getColumnNumber()
    {
        if ((currentToken != null) && (currentToken.next != null))
        {
            return currentToken.next.beginColumn;
        }
        else if (currentToken != null)
        {
            return currentToken.beginColumn;
        }
        else
        {
            return -1;
        }
    }

    /**
     * This method has the standard behavior when this object has been
     * created using the standard constructors.  Otherwise, it uses
     * "currentToken" and "expectedTokenSequences" to generate a parse
     * error message and returns it.  If this object has been created
     * due to a parse error, and you do not catch it (it gets thrown
     * from the parser), then this method is called during the printing
     * of the final stack trace, and hence the correct error message
     * gets displayed.
     * @return the current message.
     * @since 1.5
     */
    public String getMessage()
    {
        if (!specialConstructor)
        {
            StringBuilder sb = new StringBuilder(Message);
            appendTemplateInfo(sb);
            return sb.ToString();
        }

        int maxSize = 0;

        StringBuilder expected = new StringBuilder();

        foreach(int[] expectedTokenSequence in expectedTokenSequences)
        {
            if (maxSize < expectedTokenSequence.Length)
            {
                maxSize = expectedTokenSequence.Length;
            }

            for (int j = 0; j < expectedTokenSequence.Length; j++)
            {
                expected.Append(tokenImage[expectedTokenSequence[j]]).Append(" ");
            }

            if (expectedTokenSequence[expectedTokenSequence.Length - 1] != 0)
            {
                expected.Append("...");
            }

            expected.Append(eol).Append("    ");
        }

        StringBuilder retval = new StringBuilder("Encountered \"");
        Token tok = currentToken.next;

        for (int i = 0; i < maxSize; i++)
        {
            if (i != 0)
            {
                retval.Append(" ");
            }

            if (tok.kind == 0)
            {
                retval.Append(tokenImage[0]);
                break;
            }

            retval.Append(add_escapes(tok.image));
            tok = tok.next;
        }

        retval.Append("\"");
        appendTemplateInfo(retval);

        if (expectedTokenSequences.Length == 1)
        {
            retval.Append("Was expecting:").Append(eol).Append("    ");
        }
        else
        {
            retval.Append("Was expecting one of:").Append(eol).Append("    ");
        }

        // avoid JDK 1.3 StringBuffer.Append(Object o) vs 1.4 StringBuffer.Append(StringBuffer sb) gotcha.
        retval.Append(expected.ToString());
        return retval.ToString();
    }

    /**
     * @param sb
     * @since 1.5
     */
    protected void appendTemplateInfo( StringBuilder sb)
    {
        sb.Append(StringUtils.formatFileString(getTemplateName(), getLineNumber(), getColumnNumber()));
        sb.Append(eol);
    }
}
}